/**
 * java多线程模式
 * @author andy.rong
 */

package com.myjavalab.thread;

public class SingleThreadExecution {

	public static void main(String[] args) {
		System.out.println("Testing gate, enter Ctrl+C to exit");
		Gate gate = new Gate();
		new UserThread(gate, "Aaa", "Aaa").start();
		new UserThread(gate, "Bbb", "Bbb").start();
		new UserThread(gate, "Ccc", "Ccc").start();
	}
}

class Gate {
	private int counter;
	private String name;
	private String address;
	
	public void pass(String name, String address) {  //unsafe
//	public synchronized void pass(String name, String address) {		
		this.counter++;
		this.name = name;
//		try {			
//			Thread.sleep(1000);
//		}catch(InterruptedException e) {
//			
//		}
		
		this.address = address;
		check();
	}
	
	private void check() {
		if(name.charAt(0) != address.charAt(0)) {
			System.out.println("***** Broken *****" + toString());
		}
	}
	
	public synchronized String toString() {
		return "No." + counter + ": " + name + ", " + address;
	}
}

class UserThread extends Thread {
	private final Gate gate;
	private final String name;
	private final String address;
	
	public UserThread(Gate gate, String name, String address) {
		this.gate = gate;
		this.name = name;
		this.address = address;
	}
	
	public void run() {
		System.out.println(name + " started");
		while(true) {			
			gate.pass(name, address);
		}
	}
}